/* eslint-disable no-unused-vars */
/* eslint-disable react/destructuring-assignment */
/* eslint-disable no-useless-constructor */
/* eslint-disable import/no-cycle */
import React from 'react';
import DesignUtil from './common/DesignUtil';
import ControlPlus from './controls/ControlPlus';
import ControlUtil from './controls/ControlUtil';
import DesignContext from './designContext';

// 仅在designForm元素内生效，会被表单load时候解析，否则就是空内容展现
// 设计控件：声明一个语法糖
class DesignControl extends React.Component {
  // const { designtype, designdata } = this.props;
  constructor(props) {
    super(props);
    this.state = {
      control: null,
    };
  }

  componentDidMount() {
    this.init(this.props);
  }

  static getDerivedStateFromProps(nextProps, prevState) {
    // 该方法内禁止访问this
    if (
      prevState.control != null &&
      DesignUtil.objectEquals(nextProps.designdata, prevState.control.props.designdata) === false
    ) {
      prevState.control.load(nextProps.designdata);
      // 通过对比nextProps和prevState，返回一个用于更新状态的对象
      return {
        control: prevState.control,
      };
    }
    // 不需要更新状态，返回null
    return null;
  }

  init = function (props) {
    const designtype2 = props.designtype || props.designdata?.type || '';
    const c = ControlPlus.create3(designtype2, { ...props, ...{ children: props.children } }, props.designdata);
    c.data.key = props.designkey;
    this.setState({
      control: c,
    });
  };

  render() {
    return (
      <DesignContext.Consumer>
        {(context) => {
          return <>{this.state?.control?.render({ ...context, isEditState: false })}</>;
        }}
      </DesignContext.Consumer>
    );
  }
}

export default DesignControl;
